package com.hckj.jianzhijia.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.util.Stack;


public class MyActivityManager {
    private static Stack<Activity> ACTIVITY_STACK;
    private static MyActivityManager activityManagerInstance;

    private MyActivityManager() {
        ACTIVITY_STACK = new Stack<Activity>();
    }

    public static synchronized MyActivityManager getInstance() {
        if (activityManagerInstance == null) {
            activityManagerInstance = new MyActivityManager();
        }
        return activityManagerInstance;
    }

    /**
     * 添加一个Activity
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        ACTIVITY_STACK.push(activity);
        Log.e("ActivityManager", "当前Activity栈数量：" + ACTIVITY_STACK.size());
        for (int i = 0; i < ACTIVITY_STACK.size(); i++) {
            Log.e("ActivityManager", "Activity:" + i + "name:" + ACTIVITY_STACK.get(i).getClass().getSimpleName());
        }
    }

    public Activity getTopActivity() {
        if (ACTIVITY_STACK.size() == 0) {
            return null;
        } else {
            return ACTIVITY_STACK.peek();
        }
    }

    /**
     * 移除当前顶部Activity
     */
    public void finishTopActivity() {
        Activity activity = ACTIVITY_STACK.pop();
        finishActivity(activity);
        Log.e("ActivityManager", "当前Activity栈数量：" + ACTIVITY_STACK.size());
    }

    /**
     * 关闭指定Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            ACTIVITY_STACK.remove(activity);
            activity.finish();
            activity = null;
        }
        Log.e("ActivityManager", "当前Activity栈数量：" + ACTIVITY_STACK.size());
    }

    /**
     * 关闭全部Activity
     */
    public void finishAllActivity() {
        for (int i = 0; i < ACTIVITY_STACK.size(); i++) {
            Activity tempAct = ACTIVITY_STACK.get(i);
            if (tempAct != null) {
                tempAct.finish();
            }
        }
        ACTIVITY_STACK.clear();
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.restartPackage(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
        }
    }


}
